﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;
namespace lnxsj.web.Recruitment.Areas.manage.Controllers
{
    using Models;
    using Classes;
    using Filters;
    [Authorize(Roles="admin")]
    [InitializeSimpleMembership]
    
    public class userController : Controller
    {
        
        private RecrunitmenutDB db = new RecrunitmenutDB();

        //
        // GET: /manage/user/

        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        //
        // GET: /manage/user/Details/5

        public ActionResult Details(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }
        //
        // GET: 缺省用户
        [HttpGet]
        [AllowAnonymous()]
        public ActionResult CreateDefault()
        {
            TempData["extInfo"] = "目前数据库中没有管理员，请建立一个[ 超级用户 ]";
            return View("Create");
        }

        //
        // POST: 缺省用户

        [HttpPost]
        [AllowAnonymous()]
        public ActionResult CreateDefault(RegisterModel user)
        {
            if (db.Users.Count() != 0) { return Redirect("~/"); }
            if (ModelState.IsValid)
            {
                if (String.IsNullOrWhiteSpace(user.显示名)) {
                    user.显示名 = user.UserName;
                }
                if (!Roles.RoleExists("admin"))
                {
                    Roles.CreateRole("admin");
                }
                WebSecurity.CreateUserAndAccount(user.UserName, user.Password, new { 备注 = user.备注,显示名=user.显示名});
                Roles.AddUserToRole(user.UserName, "admin");
                return RedirectToAction("Index");
            }

            return View("../index");
        }
        //
        // GET: /manage/user/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /manage/user/Create

        [HttpPost]

        public ActionResult Create(RegisterModel user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    WebSecurity.CreateUserAndAccount(user.UserName, user.Password, new { 备注 = user.备注, 显示名 = user.显示名 });
                }catch(Exception e){
                    ModelState.AddModelError("",e.Message);
                    return View(user);
                }

                return RedirectToAction("Index");
            }

            return View(user);
        }

        //
        // GET: /manage/user/Edit/5

        public ActionResult Edit(int id = 0)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /manage/user/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection fc,string resetPSW)
        {
                User user=null;
                try
                {
                    user = db.Users.Find(Convert.ToInt32(fc["Id"]));


                    user.备注 = fc["备注"];
                    user.显示名 = fc["显示名"];

                    db.SaveChanges();
                    if (resetPSW == "on")
                    {
                        WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(user.登录名, 100), "123456");
                    }

                    return RedirectToAction("Index");
                }
                catch (Exception e) {
                    ModelState.AddModelError("", e.Message);
                    return View(user);
                }

                
        }


        //
        // POST: /manage/user/Delete/5


        public ActionResult Del(string id)
        {


            var s =Roles.GetRolesForUser(id);
            if (s.Length>0 && s[0] == "admin") {
                if (Request.IsAjaxRequest())
                {
                    return myAjaxResult.error("唯一管理员权限，不可删除");
                }
                else {
                    return RedirectToAction("Index");
                }
            }
            
            //坑爹的删法
            
            ((SimpleMembershipProvider)Membership.Provider).DeleteAccount(id);
            ((SimpleMembershipProvider)Membership.Provider).DeleteUser(id, true);

            if (Request.IsAjaxRequest())
            {

                    return myAjaxResult.success();

            }
            else
            {
                return RedirectToAction("Index");
            }   
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}